package com.csy.user.controller.system;

import com.csy.commons.core.domain.BaseResponse;
import com.csy.commons.core.utils.ChainedMap;
import com.csy.commons.core.utils.ServletUtils;
import com.csy.commons.dto.LoginUser;
import com.csy.commons.dto.SysMenu;
import com.csy.commons.dto.SysUser;
import com.csy.commons.framework.service.SysMenuService;
import com.csy.commons.framework.service.TokenService;
import com.csy.commons.vo.RouterVo;
import com.csy.user.entity.system.domain.vo.LoginBody;
import com.csy.user.entity.system.service.SysLoginService;

import com.csy.commons.framework.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 * @Auther: sunxx
 * @Date: 2024/1/13 - 01 - 13 - 22:45
 * @Description: com.sxx.ajcommunity.web.controller.system
 * @version: 1.0
 */
@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysMenuService sysMenuService;
    /*
    * 登录方法
    * */
    @PostMapping("/login")
    public ChainedMap login(@RequestBody LoginBody loginBody){

        //生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword()
                , loginBody.getCode(), loginBody.getUuid());

        return ChainedMap.create().set("token",token);
    }
    /*
    * 获取用户信息及其权限信息
    * */
    @GetMapping("/getInfo")
    public ChainedMap getInfo(){

        //用户信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();

        //角色集合
        Set<String> roles = permissionService.getRolePermission(user);

        //权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);

        ChainedMap map = ChainedMap.create().set("code", 200).set("msg", "操作成功");
        map.put("user",user);
        map.put("roles",roles);
        map.put("permissions",permissions);
        return map;
    }
    /*
    * 获取路由信息
    * */
    @GetMapping("/getRouters")
    public BaseResponse<List<RouterVo>> getRouters(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        com.csy.commons.dto.SysUser user = loginUser.getUser();
        //获取菜单列表
        List<SysMenu> menus = sysMenuService.selectMenuTreeByUserId(user.getUserId());
        //将获取到的菜单列表转换为 前端需要的路由列表
        List<RouterVo> routerVoList = sysMenuService.buildMenus(menus);
        return BaseResponse.success(routerVoList);
    }
}
